package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    //注入存取图片位置
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        log.info(file.toString());
        //获取上传文件名
        String originalFilename = file.getOriginalFilename();
        //使用UUID重新生成文件名，防止文件重名,处理后缀名
        String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //判断存取位置是否存在，不存在则先创建目录
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 将临时文件转存到目标文件下
        file.transferTo(new File(dir,fileName));
        return R.success(fileName);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        //设置响应图片类型
        response.setContentType("image/jpeg");
        //读取本地图片输入流，写出网络流
        try (FileInputStream fis = new FileInputStream(basePath+name);
             ServletOutputStream outputStream = response.getOutputStream()){
            byte[] bys = new byte[1024];
            int len = -1;
            while ((len = fis.read(bys)) != -1) {
                outputStream.write(bys,0,len);
                outputStream.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
